<template>
  <view class="work-page">
    <custom-navbar>
      <template #right>
        <view class="right">
          <wd-icon
            class-prefix="icon"
            name="xlxs"
            size="40rpx"
            v-if="isFile"
            @click="openFile"
          ></wd-icon>
          <wd-icon
            name="cloud-upload"
            size="46rpx"
            color="#3366ff"
            custom-style="margin-left: 32rpx;"
            v-if="workData.length"
            @click="onUpload"
          ></wd-icon>
        </view>
      </template>
    </custom-navbar>

    <!-- 数据列表 -->
    <view class="work-data-list" v-if="workData.length">
      <view class="work-data-item" v-for="item in workData" :key="item.orderId">
        <view class="title">
          <text>工艺号：{{ item.name }} </text>
          <!-- <image class="arrow" src="/static/arrow.png" mode="widthFix"/> -->
        </view>

        <view class="detail">
          <view class="label">操作时间</view>
          <view class="value"> {{ item.datetime_work1 }} </view>
        </view>
        <!-- <view class="flex-center-between f28 mt10">
          <view class="gray">操作人</view>
          <view class="">{{item.workItem.min_tork}}</view>
        </view> -->
        <view class="detail">
          <view class="label">实际扭矩值</view>
          <view class="">{{ item.real_tork || '' }}</view>
        </view>
        <view class="detail">
          <view class="label">实际角度值</view>
          <view class="value">{{ item.real_angle || '' }}</view>
        </view>
        <view class="detail">
          <view class="label">扳手标识</view>
          <view class="value">{{ item.wrench_identity }}</view>
        </view>
        <view class="detail">
          <view class="label">扳手名称</view>
          <view class="value">
            {{ item.device_name || '未命名设备'
            }}<!-- [{{ item.device_proto || '' }}] -->
          </view>
        </view>
      </view>
    </view>
    <view class="empty" v-else>
      <image class="pic" src="/src/static/images/content.png" mode="aspectFit" />
      <text class="text">暂无数据</text>
    </view>
  </view>
</template>

<script setup>
import * as XLSX from 'xlsx'
import { isNetWork } from '@/utils/system'
import { postSaveWorkDataAPI } from '@/api/apis'
import { useUserStore, useWorkStore } from '@/stores/'
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
const userStore = useUserStore()
const workStore = useWorkStore()
// 文件
const isFile = ref(false)
// 操作数据
const workData = computed(() => workStore.workList.map((item) => item.workItem) || [])
// 文件表头
const tableHeader = [
  '工位',
  '实际值',
  '扭力单位',
  '允许最低值',
  '允许最大',
  '实际角度值',
  '目标角度值',
  '角度下限',
  '角度上限',
  '组织 / 数据库 ID',
  '操作人员',
  '扳手ID',
  '操作时间',
  '说明',
  '工步明细 / 数据库 ID',
  '工步单号',
]
// 上传或导出
async function onUpload() {
  let actionType = userStore.actionType
  if (actionType === 'offline') {
    onCreateAndShare()
    return
  }
  const isConnected = await isNetWork()
  console.log('onUpload isConnected', isConnected)
  // 如果有网络
  if (isConnected) {
    const work = workStore.getWorkList()
    let data = work.map((v) => v.params)
    let res = await postSaveWorkDataAPI(data)
    console.log('res:', res)
    // if (res) {
    uni.showToast({
      title: '操作成功',
      icon: 'success',
    })
    workStore.setWorkList([])
    // } else {
    // onCreateAndShare()
    // }
  }
  // 如果没有网络，生产文件，分享给好友
  else {
    // wx.showModal({
    //   title: '提示',
    //   content: '暂无网络，请在有网络的环境操作',
    //   showCancel: false,
    // })
    // #ifndef APP || MP-WEIXIN || WEB
    uni.$globalMessage.alert({
      msg: '暂不支持离线操作',
      title: '提示',
    })
    const a = true
    if (a) {
      return
    }
    // #endif
    onCreateAndShare()
  }
}
// 打开文件
async function openFile() {
  console.log('openFile')
  uni.openDocument({
    filePath: '_doc/data.xlsx',
    fileType: 'xlsx',
    showMenu: true,
    fail: () => {
      uni.showToast({
        title: '文档打开失败！',
        icon: 'none',
      })
    },
  })
}
// 生产文件
async function onCreateAndShare() {
  const workDataList = workStore.getWorkList()
  // let { list, tableHeader } = this.data
  if (!workDataList.length) {
    uni.showToast({
      title: '暂无数据',
      icon: 'none',
    })
    return
  }
  uni.showLoading({
    title: '正在生成文件',
  })

  const rows = [tableHeader]
  workDataList.forEach((v) => {
    rows.push([
      v.workItem.orderPos,
      v.workItem.real_tork,
      v.workItem.unit,
      v.workItem.min_tork,
      v.workItem.max_tork,
      v.workItem.real_angle,
      v.workItem.target_angle,
      v.workItem.min_angle,
      v.workItem.max_angle,
      v.workItem.company_id,
      v.workItem.operator_id,
      v.workItem.wrench_identity,
      v.workItem.datetime_work1,
      v.workItem.remark,
      v.workItem.orderId,
      // v.workItem.name,
      v.workItem.orerName,
    ])
  })

  try {
    await generateExcel(rows)
    uni.showToast({
      title: '导出成功',
      icon: 'success',
    })
    workStore.setWorkList([])
  } catch (error) {
    console.log(error)
  } finally {
    uni.hideLoading()
  }
}
// 生成excel
function generateExcel(data) {
  return new Promise((resolve) => {
    // 创建工作簿
    const workbook = XLSX.utils.book_new()

    let worksheet = XLSX.utils.aoa_to_sheet(data)

    // 将工作表添加到工作簿
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

    // 生成Excel文件
    const excelBuffer = XLSX.write(workbook, {
      bookType: 'xlsx',
      type: 'array',
    })

    let blob = null
    //#ifdef MP-WEIXIN
    blob = excelBuffer
    saveExcelInWeChat(blob, 'data.xlsx', resolve)
    //#endif
    //#ifdef WEB
    blob = new Blob([excelBuffer], {
      type: 'application/octet-stream',
      // type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    saveExcelInH5(blob, 'data.xlsx', resolve)
    //#endif
    //#ifdef APP
    //安卓系统不能下载blob文件(后续是通过excelbuffer转换成blob)所以要改成base64
    //生成base64 文件
    blob = XLSX.write(workbook, {
      bookType: 'xlsx',
      type: 'base64',
    })
    saveExcelInApp(blob, 'data.xlsx', function (path) {
      console.log('result', path)
      // file:///storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/data.xlsx
      plus.runtime.openFile(path) //用第三方程序打开文件
      isFile.value = true
      resolve(path)
    })
    //#endif
  })
}

/**
 * 微信小程序保存Excel文件
 * @param {Blob} blob - Excel文件的excelBuffer对象
 * @param {String} fileName - 文件名（带后缀）
 */
function saveExcelInWeChat(blob, fileName, resolve) {
  const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`
  const fs = wx.getFileSystemManager()
  fs.writeFileSync(filePath, blob, 'utf-8')

  wx.shareFileMessage({
    filePath,
    success: function (res) {
      console.log('分享成功')
      resolve()
    },
    fail(e) {
      console.log(e)
    },
  })
}

/**
 * H5端保存Excel文件
 * @param {Blob} blob - Excel文件的Blob对象
 * @param {String} fileName - 文件名（带后缀）
 */
function saveExcelInH5(blob, fileName, resolve) {
  // 创建下载链接
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = fileName

  // 触发点击下载
  document.body.appendChild(link)
  link.click()
  resolve()
  // 清理
  setTimeout(() => {
    document.body.removeChild(link)
    URL.revokeObjectURL(link.href)
  }, 100)
}
/**
 * APP保存Excel文件
 * @param {Blob} blob - Excel文件的excelBuffer对象
 * @param {String} fileName - 文件名（带后缀）
 * @param {Function} callback - 回调函数，返回path
 */
function saveExcelInApp(blob, fileName, callback) {
  //下面是当blob是excelbuffer时，需要转成base64
  // const base64Str = btoa(String.fromCharCode.apply(null, new Uint8Array(blob)))

  // const base64Str = blob
  try {
    plus.io.requestFileSystem(plus.io.PRIVATE_DOC, function (fs) {
      fs.root.getFile(fileName, { create: true }, function (entry) {
        // 获得本地路径URL，file:///xxx/doc/1663062980631.xlsx
        var fullPath = entry.fullPath

        let platform = uni.getSystemInfoSync().platform
        console.log('platform:', platform)
        if (platform == 'android') {
          var Base64 = plus.android.importClass('android.util.Base64')
          var FileOutputStream = plus.android.importClass('java.io.FileOutputStream')
          try {
            var out = new FileOutputStream(fullPath)
            // 此处Base64.decode有长度限制，如果不能满足需求，可以考虑换成官方原生插件市场的【Base64转文件】
            var bytes = Base64.decode(blob, Base64.DEFAULT)
            out.write(bytes)
            out.close()
            // 回调
            callback && callback(entry.toLocalURL())
          } catch (e) {
            console.log(e.message)
          }
        } else if (platform == 'ios') {
          var NSData = plus.ios.importClass('NSData')
          var nsData = new NSData()
          nsData = nsData.initWithBase64EncodedStringoptions(blob, 0)
          if (nsData) {
            nsData.plusCallMethod({ writeToFile: fullPath, atomically: true })
            plus.ios.deleteObject(nsData)
          }
          // 回调
          callback && callback(entry.toLocalURL())
        }
      })
    })
  } catch (error) {
    console.log(error)
  }
}

onLoad(() => {
  // 获取上次导出数据的文件信息
  uni.getFileInfo({
    filePath: '_doc/data.xlsx',
    success: (res) => {
      console.log(res)
      isFile.value = res.size > 0
    },
    fail: (fail) => {
      console.log(fail)
      isFile.value = false
    },
  })
})
</script>

<style lang="scss" scoped>
.work-page {
  .right {
    @include flex-box-set(between);
  }
  .empty {
    // width: 100%;
    height: 30vh;
    .text {
      display: block;
      text-align: center;
      color: $text-font-color-2;
    }
  }
  .work-data-list {
    padding: 12px;
    .work-data-item {
      padding: 12px;
      // margin: 10px 0;
      margin-bottom: 14px;
      border-radius: $my-border-radius-base;
      background: $my-background-color;
      .title {
        padding-bottom: 10px;
        border-bottom: $common-border-dark;
        margin-bottom: 10px;
      }
      .detail {
        @include flex-box-set(between);
        margin-top: 4px;
        font-size: $my-text-font-size-base;
        .label {
          color: $text-font-color-2;
        }
        .value {
          flex: 1;
          margin-left: 10px;
          text-align: right;
        }
      }
    }
  }
}
</style>
